<!--
 * @Description: 告警模板配置页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <div class="btnsBar">
        <ActionBar
          :add-active="addActive"
          :del-active="delActive"
          :page-no="188"
          @add="add"
          @del="del"
        />
      </div>
    </template>
    <template v-slot:content>
      <e-table
        ref="tableData"
        rowKey="alarmTemplateId"
        :table-data="tableData"
        :table-columns="tableLabel"
        :page="currentPage"
        :size="pageSize"
        :total="totalSize"
        :loading="loading"
        :table-option="tableOption"
        @sizeChange="changePageSize"
        @pageChange="changeCurrentPage"
        @handleSelectionChange="handleSelectionChange"
      >
        <template
          slot="operate"
          slot-scope="scoped"
          v-if="scoped.row.alarmTemplateId"
        >
          <span class="table-btns-box" @click="dbHandleSee(scoped.row)">
            <i class="el-icon-view"></i>
            <span>查看</span>
          </span>
          <span
            v-if="judgePermission(188,'edit')"
            class="table-btns-box"
            @click="edit(scoped.row)"
          >
            <i class="el-icon-edit-outline"></i>
            <span>修改</span>
          </span>

          <span
            v-if="judgePermission(188,'deleteone')"
            class="table-btns-box table_del_btn"
            @click="handleDelete(scoped.row)"
          >
            <i class="el-icon-delete"></i>
            <span>删除</span>
          </span>
        </template>
      </e-table>
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText + '告警模板信息'"
        :visible.sync="showAddEditDialog"
        :before-close="addCancel"
        width="40%"
      >
        <el-form
          ref="formData"
          :rules="rules"
          label-position="left"
          :model="formData"
          class="el-form"
        >
          <el-form-item label="模板名称:" class="w50p" prop="templateName">
            <el-input
              v-model="formData.templateName"
              clearable
              :disabled="mixDialogDisabled"
            />
          </el-form-item>
          <el-form-item label="数据类型:" class="w50p" prop="dataTypeId">
            <el-select
              v-model="formData.dataTypeId"
              clearable
              placeholder="请选择数据类型"
              @change="addDataType"
              :disabled="mixDialogDisabled"
            >
              <el-option
                v-for="(item, index) in dataTypeList"
                :key="index"
                :value="item.dataTypeId"
                :label="item.dataTypeName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发送间隔:" class="w50p" prop="sendingInterval">
            <el-input
              v-model="formData.sendingInterval"
              clearable
              :disabled="mixDialogDisabled"
            />
          </el-form-item>
          <el-form-item label="滤波类型:" class="w50p" prop="filterType">
            <el-select
              v-model="formData.filterType"
              clearable
              :disabled="mixDialogDisabled"
            >
              <el-option
                v-for="(item, index) in filterTypeList"
                :key="index"
                :value="item.name"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="滤波值:" class="w50p" prop="filterValue">
            <el-input
              v-model="formData.filterValue"
              clearable
              :disabled="mixDialogDisabled"
            />
          </el-form-item>
          <el-form-item label="告警通知配置:" class="w50p">
            <el-select
              v-model="formData.noticeConfigNo"
              clearable
              :disabled="mixDialogDisabled"
            >
              <!-- @change="tifierChange" -->
              <el-option
                v-for="(item, index) in contactmanList"
                :key="index"
                :value="item.noticeConfigNo"
                :label="item.noticeConfigName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="上限列表:" class="w100p">
            <div>
              <div class="line">
                <el-input
                  v-model="basetopList.levelName"
                  clearable
                  placeholder="级别名称"
                  :disabled="mixDialogDisabled"
                />
                <el-input
                  v-model="basetopList.thresholdValue"
                  clearable
                  type="number"
                  placeholder="级别阈值"
                  :disabled="mixDialogDisabled"
                />
                <el-select
                  v-model="basetopList.alarmTypeId"
                  :disabled="mixDialogDisabled"
                >
                  <el-option
                    v-for="(item, index) in alarmTypeList"
                    :key="index"
                    :label="item.alarmTypeName"
                    :value="item.alarmTypeId"
                  />
                </el-select>
                <div
                  class="line-click"
                  @click="addtopList()"
                  v-if="
                nowChanceStau === 'add' ||
                  nowChanceStau === 'edit'
              "
                >
                  <i class="el-icon-plus"></i>
                </div>
              </div>
              <div
                v-for="(item, index) in nowtopList"
                :key="index"
                class="line"
              >
                <el-input
                  v-model="nowtopList[index].levelName"
                  clearable
                  placeholder="级别名称"
                />
                <el-input
                  v-model="nowtopList[index].thresholdValue"
                  clearable
                  type="number"
                  placeholder="级别阈值"
                />
                <el-select v-model="nowtopList[index].alarmTypeId">
                  <el-option
                    v-for="(alarmTypeitem, alarmTypeindex) in alarmTypeList"
                    :key="alarmTypeindex"
                    :label="alarmTypeitem.alarmTypeName"
                    :value="alarmTypeitem.alarmTypeId"
                  />
                </el-select>
                <div class="line-click" @click="deltopList(index)">
                  <i class="el-icon-minus"></i>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="下限列表:" class="w100p">
            <div>
              <div class="line">
                <el-input
                  v-model="basebottomList.levelName"
                  clearable
                  placeholder="级别名称"
                  :disabled="mixDialogDisabled"
                />
                <el-input
                  v-model="basebottomList.thresholdValue"
                  type="number"
                  clearable
                  placeholder="级别阈值"
                  :disabled="mixDialogDisabled"
                />
                <el-select
                  v-model="basebottomList.alarmTypeId"
                  :disabled="mixDialogDisabled"
                >
                  <el-option
                    v-for="(item, index) in alarmTypeList"
                    :key="index"
                    :label="item.alarmTypeName"
                    :value="item.alarmTypeId"
                  />
                </el-select>
                <div
                  class="line-click"
                  @click="addbottomList()"
                  v-if="
                nowChanceStau === 'add' ||
                  nowChanceStau === 'edit'
              "
                >
                  <i class="el-icon-plus"></i>
                </div>
              </div>
              <div
                v-for="(item, index) in nowbottomList"
                :key="index"
                class="line"
              >
                <el-input
                  v-model="nowbottomList[index].levelName"
                  clearable
                  placeholder="级别名称"
                />
                <el-input
                  v-model="nowbottomList[index].thresholdValue"
                  type="number"
                  clearable
                  placeholder="级别阈值"
                />
                <el-select v-model="nowbottomList[index].alarmTypeId">
                  <el-option
                    v-for="(alarmTypeitem, alarmTypeindex) in alarmTypeList"
                    :key="alarmTypeindex"
                    :label="alarmTypeitem.alarmTypeName"
                    :value="alarmTypeitem.alarmTypeId"
                  />
                </el-select>
                <div class="line-click" @click="delbottomList(index)">
                  <i class="el-icon-minus"></i>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import nowpagereq from "@/api/monitoring-alarm/alarm-template-configuration";
import contactreq from "@/api/monitoring-alarm/system-notification-configuration";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import { mymixin } from "@/utils/mixin";
import { mapGetters } from "vuex";
export default {
  name: "AlarmTemplateConfiguration",
  components: { ActionBar, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      tableLabel: [
        {
          param: "templateName",
          label: "模板名称",
          show: true,
          notSearch: true,
        },
        {
          param: "dataTypeName",
          label: "数据类别",
          show: true,
          notSearch: true,
        },
        {
          param: "sendingInterval",
          label: "发送间隔",
          show: true,
          notSearch: true,
        },
        { param: "filterType", label: "滤波类型", show: true, notSearch: true },
        { param: "filterValue", label: "滤波值", show: true, notSearch: true },
      ],
      // 表单事件
      tableOption: {
        label: "操作",
        options: [
          {
            label: "操作",
            slotName: "operate",
          },
        ],
      },
      rules: {
        templateName: [
          {
            required: true,
            message: "模板名称不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        dataTypeId: [
          {
            required: true,
            message: "数据类型不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        sendingInterval: [
          {
            required: true,
            message: "发送间隔不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        filterType: [
          {
            required: true,
            message: "滤波类型不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        filterValue: [
          {
            required: true,
            message: "滤波值不能为空！",
            trigger: ["change", "blur"],
          },
        ],
      },
      templateName: "",
      // 确认删除弹框
      delDialogVisible: false,
      // 主要联系人
      zhuyaocontactmanId: "",
      checkedGroupone: [],
      checkedGrouptwo: [],
      // 联系人可选择列表
      contactmanList: [],
      // 联系方式可选择列表
      contactmetList: [
        {
          name: "手机",
        },
        {
          name: "邮箱",
        },
        {
          name: "微信",
        },
      ],
      // 上限列表
      basetopList: {
        levelName: "",
        alarmTypeId: "",
        thresholdType: "max",
        thresholdValue: "",
      },
      flagData: {
        cidFlag: false,
        weChatFlag: false,
        phoneFlag: false,
        emailFlag: false,
      },
      nowtopList: [],
      // 下限列表
      basebottomList: {
        alarmTypeId: "",
        levelName: "",
        thresholdType: "min",
        thresholdValue: "",
      },
      nowbottomList: [],
      // 滤波类型
      nowfilterType: {},
      filterTypeList: [
        {
          name: "时间",
        },
        {
          name: "次数",
        },
      ],
      dataTypeList: [],
      // 告警类型下拉数据
      alarmTypeList: [],
      // 搜索内容
      searchList: {},
      // 选中的数据项数组 alarmContactId组成 (此数组最多为一个)
      selectIdList: [],
      dialogTitle: "",
      showAddEditDialog: false,
      flagStatus: false,
      formData: {
        alarmTemplateId: "",
        templateName: "",
        sendingInterval: "",
        filterValue: "",
        filterType: "",
        dataTypeId: "",
        dataTypeName: "",
        noticeConfigNo: "",
      },
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {
    nowChanceStau: {
      handler(val) {
        if (val === "") {
          this.nowfilterType = {};
        }
      },
    },
  },
  created() {
    // 获取表格数据
    this.queryPageList();
  },
  mounted() {
    this.getselectlist();
  },
  methods: {
    changeTableSort(column) {
      this.sortList = column.order
        ? [
            {
              property: column.prop,
              direction: column.order == "ascending" ? "asc" : "desc",
            },
          ]
        : [];
      this.queryPageList();
    },
    // 添加一条上限数据
    addtopList() {
      if (this.nowChanceStau !== "add" && this.nowChanceStau !== "edit") {
        return;
      }
      let addvalue = {
        alarmTypeId: "",
        levelName: "",
        thresholdType: "max",
        thresholdValue: "",
      };
      this.nowtopList.push(addvalue);
    },
    // 删除一条上限数据
    deltopList(i) {
      if (this.nowChanceStau !== "add" && this.nowChanceStau !== "edit") {
        return;
      }
      this.nowtopList.splice(i, 1);
    },
    // 添加一条下限数据
    addbottomList() {
      if (this.nowChanceStau !== "add" && this.nowChanceStau !== "edit") {
        return;
      }
      let addvalue = {
        alarmTypeId: "",
        levelName: "",
        thresholdType: "min",
        thresholdValue: "",
      };
      this.nowbottomList.push(addvalue);
    },
    // 添加一条下限数据
    delbottomList(i) {
      if (this.nowChanceStau !== "add" && this.nowChanceStau !== "edit") {
        return;
      }
      this.nowbottomList.splice(i, 1);
    },
    // 获取下拉数据
    getselectlist() {
      // 获取所有数据类型
      nowpagereq.getalldatalist().then((res) => {
        this.dataTypeList = res.data;
      });
      // 获取所有联系人
      contactreq
        .querybycondition({ organizationNo: sessionStorage.organizationNo })
        .then((res) => {
          this.contactmanList = res.data;
        });
    },
    async tifierChange(item) {
      if (item) {
        this.flagStatus = true;
        const { data: rs } = await contactreq.queryByNo(item);
        let flagData = JSON.parse(JSON.stringify(rs));
        this.flagData = flagData;
      } else {
        this.flagStatus = false;
        this.flagData = {
          cidFlag: false,
          weChatFlag: false,
          phoneFlag: false,
          emailFlag: false,
        };
      }
    },
    // 将选择的数据类别添加到表单中 --获取告警类型列表
    addDataType(e) {
      this.alarmTypeList = [];
      this.basetopList = [];
      this.basebottomList = [];
      this.nowbottomList = [];
      this.nowtopList = [];
      if (this.nowChanceStau === "add" || this.nowChanceStau === "edit") {
        this.dataTypeList.forEach((el) => {
          if (el.dataTypeId === e) {
            this.formData.dataTypeId = el.dataTypeId;
            this.formData.dataTypeName = el.dataTypeName;
          }
        });
      }
    },
    // 处理数据类型数据
    chancealarmtype(list) {
      let newlist = [];
      list.forEach((item, index) => {
        newlist.push(item.alarmType);
      });
      this.alarmTypeList = newlist;
    },
    // 获取表格数据
    queryPageList(e) {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
      };
      nowpagereq.getlist(params).then((res) => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("查询失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        console.log("queryPageList", this.tableData);
        this.addblankmet();
        this.resetActionBar();
      });
    },
    search() {
      this.currentPage = 1;
      this.queryPageList();
    },

    // 添加
    add() {
      this.addActive = false;
      this.basetopList = {};
      this.nowtopList = [];
      this.alarmTypeList = [];
      this.nowbottomList = [];
      this.basebottomList = {};
      this.formData = {};
      this.openDialog("add");
      this.titleText = "新增";
    },
    // 取消
    // cancel() {
    //   this.closeDialog();
    //   this.formData = {}
    // },
    handleEdit(zhrow) {
      this.templateName = zhrow.templateName;
      let row = JSON.parse(JSON.stringify(zhrow));
      if (row.alarmTemplateId) {
        this.formData = {
          alarmTemplateId: row.alarmTemplateId,
          templateName: row.templateName,
          sendingInterval: row.sendingInterval,
          filterValue: row.filterValue,
          filterType: row.filterType,
          dataTypeId: row.dataTypeId,
          dataTypeName: row.dataTypeName,
          noticeConfigNo: row.noticeConfigNo,
        };
        this.formData = { ...this.formData };
        nowpagereq.getalarmTypelist(row.dataTypeId).then((res) => {
          let data = res.data;
          this.chancealarmtype(data);
        });
        this.addDataType({ name: row.dataTypeName, value: row.dataTypeId });
        row.alarmTemplateThresholdList.forEach((item) => {
          if (item.charge === true) {
            this.zhuyaocontactmanId = item.alarmContactId;
            this.checkedGroupone = [];
            // 联系方式的赋值
            if (item.sendPhone === true) {
              this.checkedGroupone.push(0);
            }
            if (item.sendEmail === true) {
              this.checkedGroupone.push(1);
            }
            if (item.sendWeChat === true) {
              this.checkedGroupone.push(2);
            }
          }
          if (item.charge === false) {
            this.qitacontactmanId = item.alarmContactId;
            this.checkedGrouptwo = [];
            // 联系方式的赋值
            if (item.sendPhone === true) {
              this.checkedGrouptwo.push(0);
            }
            if (item.sendEmail === true) {
              this.checkedGrouptwo.push(1);
            }
            if (item.sendWeChat === true) {
              this.checkedGrouptwo.push(2);
            }
          }
        });
        let mainlist = row.alarmTemplateThresholdList;
        // 上限列表和下限列表的赋值
        this.basetopList = {
          levelName: "",
          alarmTypeId: "",
          thresholdType: "max",
          thresholdValue: "",
        };
        this.nowtopList = [];
        this.basebottomList = {
          levelName: "",
          alarmTypeId: "",
          thresholdType: "min",
          thresholdValue: "",
        };
        this.nowbottomList = [];
        if (mainlist) {
          for (var i = 0; i < mainlist.length; i++) {
            if (mainlist[i].thresholdType === "max") {
              if (this.basetopList.levelName.length === 0) {
                this.basetopList = mainlist[i];
              } else {
                this.nowtopList.push(mainlist[i]);
              }
            } else if (mainlist[i].thresholdType === "min") {
              if (this.basebottomList.levelName.length === 0) {
                this.basebottomList = mainlist[i];
              } else {
                this.nowbottomList.push(mainlist[i]);
              }
            }
          }
        }
      }
    },
    dbHandleSee(row) {
      this.mixDialogDisabled = true;
      this.formData = {
        alarmTemplateId: row.alarmTemplateId,
        templateName: row.templateName,
        sendingInterval: row.sendingInterval,
        filterValue: row.filterValue,
        filterType: row.filterType,
        dataTypeId: row.dataTypeId,
        dataTypeName: row.dataTypeName,
        noticeConfigNo: row.noticeConfigNo,
      };
      let mainlist = row.alarmTemplateThresholdList;
      // 上限列表和下限列表的赋值
      this.basetopList = {
        levelName: "",
        alarmTypeId: "",
        thresholdType: "max",
        thresholdValue: "",
      };
      this.nowtopList = [];
      this.basebottomList = {
        levelName: "",
        alarmTypeId: "",
        thresholdType: "min",
        thresholdValue: "",
      };
      this.nowbottomList = [];
      if (mainlist) {
        for (var i = 0; i < mainlist.length; i++) {
          if (mainlist[i].thresholdType === "max") {
            if (this.basetopList.levelName.length === 0) {
              this.basetopList = mainlist[i];
            } else {
              this.nowtopList.push(mainlist[i]);
            }
          } else if (mainlist[i].thresholdType === "min") {
            if (this.basebottomList.levelName.length === 0) {
              this.basebottomList = mainlist[i];
            } else {
              this.nowbottomList.push(mainlist[i]);
            }
          }
        }
      }
      this.showAddEditDialog = true;
    },
    handleSelectionChange(list) {
      this.selectIdList = [];
      let notvalue = true;
      this.selectIdList = list.map((item) => {
        if (item.alarmTemplateId) {
          return item.alarmTemplateId;
        } else {
          notvalue = false;
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return;
      }
      if (this.selectIdList) {
        if (this.selectIdList.length > 0) this.delActive = true;
        else this.delActive = false;
      }
    },
    delmessage() {
      nowpagereq.dellist(this.selectIdList).then((res) => {
        if (res.code === 1) {
          this.$message.success("删除成功");
          this.queryPageList();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    handleDelete(data) {
      // nowpagereq.dellist([data.alarmTemplateId]).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success("删除成功");
      //     this.queryPageList();
      //   } else {
      //     this.$message.error("删除失败");
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          nowpagereq.dellist([data.alarmTemplateId]).then((res) => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.queryPageList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    save() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let editparams = {
              alarmTemplateSendMapperList: [
                // 主要联系人
                {
                  alarmContactId: this.zhuyaocontactmanId,
                  charge: true,
                  sendPhone: false,
                  sendEmail: false,
                  sendWeChat: false,
                },
                // 其他联系人
                {
                  alarmContactId: this.qitacontactmanId,
                  charge: false,
                  sendPhone: false,
                  sendEmail: false,
                  sendWeChat: false,
                },
              ],
              alarmTemplateThresholdList: [],
              ...this.formData,
            };
            if (editparams.alarmTemplateSendMapperList === []) {
              delete editparams.alarmTemplateSendMapperList;
            }
            this.basetopList["thresholdType"] = "max";
            this.basebottomList["thresholdType"] = "min";
            let newlevellist = [
              // 上限数据
              { ...this.basetopList },
              ...this.nowtopList,
              { ...this.basebottomList },
              // 下限数据
              ...this.nowbottomList,
            ];
            newlevellist.forEach((el) => {
              editparams["alarmTemplateThresholdList"].push(el);
            });
            if (newlevellist === []) {
              delete editparams.alarmTemplateThresholdList;
            }
            // 编辑接口
            nowpagereq.editlist(editparams).then((res) => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.closeDialog();
                this.queryPageList();
              } else {
                this.$message.error("修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let addparams = {
              alarmTemplateSendMapperList: [],
              alarmTemplateThresholdList: [],
              ...this.formData,
            };
            if (addparams.alarmTemplateSendMapperList === []) {
              delete addparams.alarmTemplateSendMapperList;
            }
            this.basetopList["thresholdType"] = "max";
            this.basebottomList["thresholdType"] = "min";
            let newlevellist = [
              // 上限数据
              { ...this.basetopList },
              ...this.nowtopList,
              { ...this.basebottomList },
              // 下限数据
              ...this.nowbottomList,
            ];
            newlevellist.forEach((el) => {
              addparams["alarmTemplateThresholdList"].push(el);
            });
            if (newlevellist === []) {
              delete addparams.alarmTemplateThresholdList;
            }
            // console.log(addparams); return
            nowpagereq.addlist(addparams).then((res) => {
              if (res.code === 1) {
                this.$message.success("新增成功！");
                this.closeDialog();
                this.queryPageList();
              } else {
                this.$message.error("新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    openDialog(type) {
      this.showAddEditDialog = true;
      this.$nextTick(() => {
        this.formData = { ...this.formData };
        this.$refs.formData.resetFields();
      });
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.$nextTick(() => {
        this.$refs.formData.resetFields();
      });
      this.showAddEditDialog = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
    addCancel() {
      this.formData = {};
      this.closeDialog("add");
      this.addActive = true;
    },
  },
};
</script>

<style scoped lang="scss">
.line {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
  .line-click {
    width: 90px;
    height: 30px;
    // background-color: aqua;
    display: flex;
    justify-content: center;
    align-items: center;
    border: snow 1px solid;
    border-radius: 50%;
    margin-bottom: 10px;
    margin-top: 5px;
    margin-left: 5px;
    cursor: pointer;
  }
}
</style>
